package com.hirsi.common.core.validator;

import cn.hutool.core.util.ArrayUtil;
import com.hirsi.common.core.validator.annotation.FixedValue;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class FixedValueValidator implements ConstraintValidator<FixedValue, Object> {

    private Boolean ignoreNull;

    private int[] intValues;

    private String[] strValues;

    @Override
    public void initialize(FixedValue constraintAnnotation) {
        ignoreNull = constraintAnnotation.ignoreNull();
        intValues = constraintAnnotation.intValues();
        strValues = constraintAnnotation.strValues();
    }

    @Override
    public boolean isValid(Object o, ConstraintValidatorContext constraintValidatorContext) {
        if ((o == null && ignoreNull)
        || (o instanceof Integer && ArrayUtil.isNotEmpty(intValues) && ArrayUtil.contains(intValues, (Integer) o))
        || (o instanceof String && ArrayUtil.isNotEmpty(strValues) && ArrayUtil.contains(strValues, o))) return true;
        return false;
    }
}
